package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.AppAddHandlerRecordBo;
import org.dromara.system.domain.bo.AppAddWarehouseRecordBo;
import org.dromara.system.mapper.*;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.AppWarehouseRecordBo;
import org.dromara.system.domain.vo.AppWarehouseRecordVo;
import org.dromara.system.service.IAppWarehouseRecordService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 入库记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppWarehouseRecordServiceImpl implements IAppWarehouseRecordService {

    private final AppWarehouseRecordMapper baseMapper;
    private final AppOrderMapper appOrderMapper;
    private final AppWarehouseMapper appWarehouseMapper;
    private final AppProcurementPlanMapper appProcurementPlanMapper;
    private final AppProcurementDetailMapper appProcurementDetailMapper;

    /**
     * 查询入库记录
     *
     * @param id 主键
     * @return 入库记录
     */
    @Override
    public AppWarehouseRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询入库记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 入库记录分页列表
     */
    @Override
    public TableDataInfo<AppWarehouseRecordVo> queryPageList(AppWarehouseRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppWarehouseRecord> lqw = buildQueryWrapper(bo);
        Page<AppWarehouseRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的入库记录列表
     *
     * @param bo 查询条件
     * @return 入库记录列表
     */
    @Override
    public List<AppWarehouseRecordVo> queryList(AppWarehouseRecordBo bo) {
        LambdaQueryWrapper<AppWarehouseRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppWarehouseRecord> buildQueryWrapper(AppWarehouseRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppWarehouseRecord> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppWarehouseRecord::getId);
        lqw.eq(bo.getStorageType() != null, AppWarehouseRecord::getStorageType, bo.getStorageType());
        lqw.eq(StringUtils.isNotBlank(bo.getPlanCode()), AppWarehouseRecord::getPlanCode, bo.getPlanCode());
        lqw.eq(bo.getLoadTotalWeight() != null, AppWarehouseRecord::getLoadTotalWeight, bo.getLoadTotalWeight());
        lqw.eq(bo.getLoadTareWeight() != null, AppWarehouseRecord::getLoadTareWeight, bo.getLoadTareWeight());
        lqw.eq(bo.getLoadNetWeight() != null, AppWarehouseRecord::getLoadNetWeight, bo.getLoadNetWeight());
        lqw.eq(bo.getWeighingTotalWeight() != null, AppWarehouseRecord::getWeighingTotalWeight, bo.getWeighingTotalWeight());
        lqw.eq(bo.getTareWeight() != null, AppWarehouseRecord::getTareWeight, bo.getTareWeight());
        lqw.eq(bo.getMaterialUnloadWeight() != null, AppWarehouseRecord::getMaterialUnloadWeight, bo.getMaterialUnloadWeight());
        lqw.eq(bo.getRoadLoss() != null, AppWarehouseRecord::getRoadLoss, bo.getRoadLoss());
        lqw.eq(bo.getDeductWeight() != null, AppWarehouseRecord::getDeductWeight, bo.getDeductWeight());
        lqw.eq(bo.getNetPurchaseWeight() != null, AppWarehouseRecord::getNetPurchaseWeight, bo.getNetPurchaseWeight());
        lqw.eq(bo.getPackageNum() != null, AppWarehouseRecord::getPackageNum, bo.getPackageNum());
        lqw.eq(StringUtils.isNotBlank(bo.getWarehouseCode()), AppWarehouseRecord::getWarehouseCode, bo.getWarehouseCode());
        lqw.eq(StringUtils.isNotBlank(bo.getWarehouseAdmin()), AppWarehouseRecord::getWarehouseAdmin, bo.getWarehouseAdmin());
        lqw.eq(StringUtils.isNotBlank(bo.getWarehouseCarPlate()), AppWarehouseRecord::getWarehouseCarPlate, bo.getWarehouseCarPlate());
        lqw.eq(bo.getWarehouseDate() != null, AppWarehouseRecord::getWarehouseDate, bo.getWarehouseDate());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), AppWarehouseRecord::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterialType()), AppWarehouseRecord::getMaterialType, bo.getMaterialType());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), AppWarehouseRecord::getCategory, bo.getCategory());
        lqw.like(StringUtils.isNotBlank(bo.getWarehouseName()), AppWarehouseRecord::getWarehouseName, bo.getWarehouseName());
        lqw.eq(bo.getStorageQuantity() != null, AppWarehouseRecord::getStorageQuantity, bo.getStorageQuantity());
        return lqw;
    }

    /**
     * 新增入库记录
     *
     * @param bo 入库记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppWarehouseRecordBo bo) {
        AppWarehouseRecord add = MapstructUtils.convert(bo, AppWarehouseRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改入库记录
     *
     * @param bo 入库记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppWarehouseRecordBo bo) {
        AppWarehouseRecord update = MapstructUtils.convert(bo, AppWarehouseRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppWarehouseRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除入库记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> enterWarehouse(String orderId) {
        //查询订单
        LambdaQueryWrapper<AppOrder> ao = new LambdaQueryWrapper<>();
        ao.eq(AppOrder::getOrderId,orderId);
        AppOrder appOrder = appOrderMapper.selectOne(ao);
        if(appOrder == null){
            return R.fail("订单不存在");
        }
        //如果订单没有送到 无法入库
        if(appOrder.getOrderStatus() != 5){
            return R.fail("订单没有送到无法入库");
        }
        //入库后修改仓库记录数
        Long warehouseId = appOrder.getWarehouseId();
        //查询采购计划
        LambdaQueryWrapper<AppProcurementPlan> ap = new LambdaQueryWrapper<>();
        ap.eq(AppProcurementPlan::getPlanCode,appOrder.getPlanId());
        AppProcurementPlan appProcurementPlan = appProcurementPlanMapper.selectOne(ap);
        //查询采购数量
        LambdaQueryWrapper<AppProcurementDetail> appProcurementDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appProcurementDetailLambdaQueryWrapper.eq(AppProcurementDetail::getPlanCode,appProcurementPlan.getPlanCode());
        List<AppProcurementDetail> appProcurementDetails = appProcurementDetailMapper.selectList(appProcurementDetailLambdaQueryWrapper);
        if (appProcurementDetails == null){
            return R.fail("采购数量不存在");
        }
        for (AppProcurementDetail appProcurementDetail : appProcurementDetails) {
            //采购原料类型
            Long materialTypeId = appProcurementDetail.getMaterialTypeId();
            //计划采购吨数
            Long plannedWeight = appProcurementDetail.getPlannedWeight();
            //修改仓库记录数
            LambdaQueryWrapper<AppWarehouse> aqw = new LambdaQueryWrapper<>();
            LambdaUpdateWrapper<AppWarehouse> auw = new LambdaUpdateWrapper<>();
            aqw.eq(AppWarehouse::getId,warehouseId);
            AppWarehouse appWarehouse1 = appWarehouseMapper.selectOne(aqw);
            if (appWarehouse1 == null){
                return R.fail("仓库不存在");
            }
            auw.eq(AppWarehouse::getId,warehouseId);
            auw.eq(AppWarehouse::getGoodsType,materialTypeId);
            auw.set(AppWarehouse::getStock,appWarehouse1.getStock()+plannedWeight);
            appWarehouseMapper.update(auw);
        }
        appOrder.setOrderStatus(6L);
        appOrderMapper.updateById(appOrder);
        return R.ok();
    }

    @Override
    public R<Void> createWareHouse(AppAddHandlerRecordBo appAddWarehouseRecordBo) {
        //手动入库
        //根据仓库id 查询仓库
        LambdaQueryWrapper<AppWarehouse> appWarehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getStoreId,appAddWarehouseRecordBo.getStoreId());
        appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getTenantId,appAddWarehouseRecordBo.getTenantId());
        List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(appWarehouseLambdaQueryWrapper);
        if (CollUtil.isEmpty(appWarehouses)){
            return R.fail("仓库不存在");
        }
        AppWarehouse appWarehouse1 = appWarehouses.stream().filter(appWarehouse -> appWarehouse.getMaterialId()
            .equals(appAddWarehouseRecordBo.getMaterialId())).findFirst().get();

        //添加入库记录
        AppWarehouseRecord appWarehouseRecord = new AppWarehouseRecord();
        appWarehouseRecord.setStorageType(1L);
        appWarehouseRecord.setWarehouseId(appWarehouse1.getStoreId());
        appWarehouseRecord.setLoadTotalWeight(appAddWarehouseRecordBo.getStorageWeight());
        appWarehouseRecord.setStorageQuantity(appAddWarehouseRecordBo.getStorageWeight());
        appWarehouseRecord.setMaterialType(appWarehouse1.getMaterialId());
        appWarehouseRecord.setCategory(appWarehouse1.getGoodsType());
        appWarehouseRecord.setRemark(appAddWarehouseRecordBo.getRemark());
        appWarehouseRecord.setWarehouseName(appWarehouse1.getName());
        if (baseMapper.insert(appWarehouseRecord) > 0){
            appWarehouse1.setStock(appWarehouse1.getStock()+appAddWarehouseRecordBo.getStorageWeight());
            appWarehouseMapper.updateById(appWarehouse1);
        }
        return R.ok();
    }
}
